const fs = require('fs');
const http = require('http');
const path = require('path');

/**
 * 使用了递归查找
 * 引入res是为了解决异步问题
 * @param {扩展名数组} extN 
 * @param {文件路径} phs 
 * @param {当前扩展名索引} num 
 * @param {响应对象} res 
 * @returns 
 */
function readByext(extN,phs,num,res){
    if(extN.length == num) return res.end("<h1>404</h1><p>Not found</p>");
    fs.readFile(phs+extN[num],(err,data)=>{
            return err?readByext(extN,phs,num+1,res):res.end(data);
    })
}
http.createServer((req,res)=>{
    let ph = path.join(__dirname,req.url == '/'?"index.html":req.url)
    console.log("请求路径为："+ph);
    fs.stat(ph,(err,data)=>{
        if(err){
            console.log("读取异常，尝试拼接扩展名");
            var extN = ['.html','.txt','.md'];
            return path.extname(ph) == ''? readByext(extN,ph,0,res):res.end(`<h1>404 Not found</h1>`);
        }
        //文件夹=》index.html
        if(data.isDirectory()){
            console.log("该路径为文件夹");
            fs.readdir(ph,(rerr,rdata)=>{
                if(rerr) return res.end(rerr+"");
                console.log("文件夹读取成功");
                if(rdata.length == 0)return res.end(`<h1>404 Not found</h1>`);
                if(rdata.includes("index.html")){
                    fs.readFile(path.join(ph,"index.html"),(ierr,idata)=>{
                        return res.end(ierr?ierr+"":idata);
                    })
                }else{
                    return res.end(`<h1>404 Not found</h1>`)
                }
            })
        }else{
            console.log("精准查找文件");
            fs.readFile(ph,(err,data)=>{                    
                return res.end(err?`<h1>404 Not found</h1><p${err}</p>`:data);
            })
        }
    })
}).listen(80,()=>{
    console.log("http://127.0.0.1 is running");
})
